package cn.tedu.boot3.controller;


import cn.tedu.boot3.entity.Product;
import cn.tedu.boot3.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
//此注解相当于在Controller的基础上,在每个方法的上面都添加了@ResponseBody注解
public class ProductConteoller {
    //自动装配,是spring框架中提供的注释,添加了此注解后Mybatis框架会根据此接口
    //创建实现类,并且实例化了此实现类,此时mapper变量已经有值,可以调用里面的方法
    @Autowired
    ProductMapper mapper;

    @RequestMapping("/insert")
    public String insert(Product product) {
        System.out.println("product = " + product);
        mapper.insert(product);
        return "添加成功";
    }

    @RequestMapping("/select")
    public String select() {
        List<Product> list = mapper.select();

        /**************************************************/
        String html = "<table border='1'>";
        html += "<caption>商品列表</caption>";
        html += "<tr><th>id</th><th>标题</th><th>价格</th><th>库存</th><th>操作</th></tr>";
        //遍历集合中商品的信息 然后往表格标签里面添加tr和td
        for (Product p : list) {
            html += "<tr>";
            html += "<td>" + p.getId() + "</td>";
            html += "<td>" + p.getTitle() + "</td>";
            html += "<td>" + p.getPrice() + "</td>";
            html += "<td>" + p.getNum() + "</td>";
            html += "<td><a href='/delete?id=" + p.getId() + "'>删除</a></td>";
            html += "</tr>";
        }
        html += "</table>";
        return html;
        /**************************************************/

    }

    @RequestMapping("/delete")
    public String delete(int id) {

        mapper.deleteById(id);
        return "删除完成!<a href='/select'>返回列表页面</a>";
    }

    @RequestMapping("/update")
    public String update(Product product){
        mapper.update(product);
        return "修改成功~<a href='/select'>返回列表页面<a>";
    }

}
